package com.evan.review.ipc;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.evan.review.R;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;

/**
 * Socket通信示例
 * 展示如何使用Socket进行进程间通信
 * 
 * 在本示例中，我们将:
 * 1. 创建一个本地Socket服务器
 * 2. 实现客户端连接到服务器
 * 3. 展示数据的发送和接收
 */
public class SocketDemoActivity extends AppCompatActivity {
    private static final String TAG = "SocketDemoActivity";
    private static final int SERVER_PORT = 8888;

    private TextView tvStatus;
    private TextView tvMessages;
    private EditText etMessage;
    private Button btnStartServer;
    private Button btnConnectClient;
    private Button btnSendMessage;
    
    private boolean isServerRunning = false;
    private ServerSocket serverSocket;
    private Socket clientSocket;
    private PrintWriter output;
    private BufferedReader input;
    private ServerThread serverThread;
    private ClientThread clientThread;
    
    private final Handler mainHandler = new Handler(Looper.getMainLooper());
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_socket_demo);
        
        tvStatus = findViewById(R.id.tv_socket_status);
        tvMessages = findViewById(R.id.tv_socket_messages);
        etMessage = findViewById(R.id.et_socket_message);
        btnStartServer = findViewById(R.id.btn_start_server);
        btnConnectClient = findViewById(R.id.btn_connect_client);
        btnSendMessage = findViewById(R.id.btn_send_message);
        
        btnStartServer.setOnClickListener(v -> startSocketServer());
        btnConnectClient.setOnClickListener(v -> connectToServer());
        btnSendMessage.setOnClickListener(v -> sendMessage());
        
        updateStatus("未连接");
        btnConnectClient.setEnabled(false);
        btnSendMessage.setEnabled(false);
    }
    
    private void startSocketServer() {
        if (isServerRunning) {
            Toast.makeText(this, "服务器已在运行", Toast.LENGTH_SHORT).show();
            return;
        }
        
        serverThread = new ServerThread();
        serverThread.start();
        btnStartServer.setEnabled(false);
        btnConnectClient.setEnabled(true);
        updateStatus("服务器已启动，等待连接...");
    }
    
    private void connectToServer() {
        if (clientSocket != null && clientSocket.isConnected()) {
            Toast.makeText(this, "已连接到服务器", Toast.LENGTH_SHORT).show();
            return;
        }
        
        clientThread = new ClientThread();
        clientThread.start();
        btnConnectClient.setEnabled(false);
    }
    
    private void sendMessage() {
        if (output == null) {
            Toast.makeText(this, "未连接到服务器", Toast.LENGTH_SHORT).show();
            return;
        }
        
        String message = etMessage.getText().toString().trim();
        if (message.isEmpty()) {
            // 如果消息为空，发送随机测试消息
            message = "测试消息 #" + new Random().nextInt(1000);
        }
        
        final String finalMessage = message;
        new Thread(() -> {
            output.println(finalMessage);
            output.flush();
            
            mainHandler.post(() -> {
                appendMessage("发送: " + finalMessage);
                etMessage.setText("");
            });
        }).start();
    }
    
    private void updateStatus(final String status) {
        mainHandler.post(() -> tvStatus.setText("状态: " + status));
    }
    
    private void appendMessage(final String message) {
        mainHandler.post(() -> {
            String currentText = tvMessages.getText().toString();
            tvMessages.setText(currentText + "\n" + message);
        });
    }
    
    // 服务器线程
    private class ServerThread extends Thread {
        @Override
        public void run() {
            try {
                serverSocket = new ServerSocket(SERVER_PORT);
                isServerRunning = true;
                updateStatus("服务器已启动于端口 " + SERVER_PORT);
                
                // 等待客户端连接
                Socket socket = serverSocket.accept();
                
                // 获取输入输出流
                input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                
                updateStatus("客户端已连接: " + socket.getInetAddress());
                
                // 监听客户端消息
                String message;
                while (isServerRunning && (message = input.readLine()) != null) {
                    final String receivedMessage = message;
                    appendMessage("接收: " + receivedMessage);
                }
            } catch (IOException e) {
                Log.e(TAG, "服务器错误: " + e.getMessage());
                updateStatus("服务器错误: " + e.getMessage());
            } finally {
                stopServer();
            }
        }
    }
    
    // 客户端线程
    private class ClientThread extends Thread {
        @Override
        public void run() {
            try {
                // 连接到本地服务器
                clientSocket = new Socket("localhost", SERVER_PORT);
                output = new PrintWriter(new BufferedWriter(
                        new OutputStreamWriter(clientSocket.getOutputStream())), true);
                
                updateStatus("已连接到服务器");
                
                mainHandler.post(() -> {
                    btnSendMessage.setEnabled(true);
                    appendMessage("连接已建立");
                });
            } catch (IOException e) {
                Log.e(TAG, "客户端连接错误: " + e.getMessage());
                updateStatus("连接错误: " + e.getMessage());
                
                mainHandler.post(() -> 
                    btnConnectClient.setEnabled(true)
                );
            }
        }
    }
    
    private void stopServer() {
        isServerRunning = false;
        try {
            if (serverSocket != null && !serverSocket.isClosed()) {
                serverSocket.close();
            }
            if (clientSocket != null && !clientSocket.isClosed()) {
                clientSocket.close();
            }
            if (input != null) {
                input.close();
            }
            if (output != null) {
                output.close();
            }
        } catch (IOException e) {
            Log.e(TAG, "关闭服务器错误: " + e.getMessage());
        }
        
        mainHandler.post(() -> {
            btnStartServer.setEnabled(true);
            btnConnectClient.setEnabled(false);
            btnSendMessage.setEnabled(false);
            updateStatus("服务器已停止");
        });
    }
    
    @Override
    protected void onDestroy() {
        stopServer();
        super.onDestroy();
    }
} 